<template>
	<!-- 菜品区域 -->
	<view class="ld">
		<view class="left" v-if="menuItem.length > 0">
			<scroll-view :scroll-y="true" :scroll-with-animation="true" :scroll-into-view="clickToId"
				:style="{ height: windowHeight }">
				<view v-for="(item, index) in menuItem" :key="index">
					<view :class="['title', { active: index === currentNum }]" :id="'to' + index" @click="setId(index)">
						{{
							item.foodPackageTypeName || item.foodTypeName }}
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="right">
			<scroll-view :scroll-into-view="clickId" @scroll="scroll" :scroll-with-animation="true" :scroll-y="true"
				:style="{ height: windowHeight }">
				<view v-for="(item, index) in menuItem" :key="index" class="goods">
					<view class="title,right_title" :id="'po' + index">{{
						item.foodPackageTypeName || item.foodTypeName
					}}</view>
					<view v-for="(it, idx) in (item.foodPackageTypeName ? item.foodpackagelist : item.foodlist)" :key="idx"
						class="goods-item">
						<view class="goods-info">
							<image
								:src="!it.imgPath ? 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg' : ('https://api.victorick.com:8222/' + it.imgPath)"
								alt="餐品" class="image"
								@click="clickImg(('https://api.victorick.com:8222/' + it.imgPath), it.imgPath)"
								mode="aspectFit" />
							<view class="conent">
								<view class="name">{{ it.foodPackageName || it.foodName }}</view>
								<view class="label" v-if="it.foodPackageLabel || it.foodLabel">
									{{ it.foodPackageLabel || it.foodLabel }}
								</view>
								<text class="price"><text class="price_color">￥{{ it.defaultPriceStr }}</text>/份</text>
							</view>
						</view>
						<view>
							<uni-number-box class="slot-number"
								v-if="storeCart.cartNew.find((i) => (i.goodsInfo.foodId == it.foodSerials || i.goodsInfo.foodId == it.foodPackageSerials))"
								:value="storeCart.cartNew.find((i) => (i.goodsInfo.foodId == it.foodSerials || i.goodsInfo.foodId == it.foodPackageSerials)).goodsInfo.num || 0"
								@change="(value) => {
									twobindChange(
										value,
										it
									);
								}
									" background="#2979FF" color="#fff" :min="0" :max="99" />
							<button class="add-btn" type="default" size="mini" @click="onBtn(it, item)"
								v-if="!storeCart.cartNew.some((i) => (i.goodsInfo.foodId === it.foodSerials || i.goodsInfo.foodId === it.foodPackageSerials))">
								添加
							</button>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 单品 -->
		<uni-popup ref="addCartPopup" type="center" background-color="#fff" class="add_box">
			<view>
				<image
					:src="!foodItem.imgPath ? 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg' : ('https://api.victorick.com:8222/' + foodItem.imgPath)"
					mode="scaleToFill" />
			</view>
			<view class="goods-name">{{ foodItem.name }}</view>
			<view class="specifications">规格： <text>{{ foodItem.amount }}{{ foodItem.unit }}/份</text></view>
			<view class="add-box">
				<text class="price"><text class="price_color">￥{{ foodItem.defaultPrice }}</text></text>
				<uni-number-box v-model="goodsInfo.num" background="#2979FF" color="#fff" :min="1"
					:max="foodItem.dayOrderNumberLimit || 99" />
			</view>
			<button type="default" class="add-cart" @click="debounceFunc">
				加入购物车
			</button>
		</uni-popup>
		<!-- 套餐 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff" class="meal">
			<scroll-view scroll-y class="scroll">
				<view class="close" @click="onCloseBtn">
					<image src="../../static/images/del.png" class="img" />
				</view>
				<view class="title">{{ foodPackageItem.foodPackageName }}</view>
				<view v-for="(item, index) in foodPackageUnit?.foodlistdata" :key="index">
					<view>{{ item.groupName }}<text>(请选择{{ item.groupChooseFoodNum }}份)</text></view>
					<uni-grid :column="4" :show-border="false" :square="false" @change="change">
						<uni-grid-item v-for="(it, index) in item.foodlist" :index="index" :key="index">
							<view class="grid-item-box" @click="fn(it, item.groupChooseFoodNum, item.foodlist.length, item)"
								:mark:index="index">
								<view class="picture">
									<image class="image" mode="aspectFill"
										:src="!it.imgPath ? 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg' : ('https://api.victorick.com:8222/' + it.imgPath)" />
									<view class="icon icon-duigou-copy dot" :class="{ active: it.checked }"></view>
								</view>
								<text class="text">{{ it.foodName }}</text>
							</view>
						</uni-grid-item>
					</uni-grid>
				</view>
			</scroll-view>
			<!-- 底部按钮 -->
			<view class="footer">
				<view>
					<view style="display: flex">规格<view class="spec">份</view>
					</view>
					<view style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            ">
						<view>￥ {{ foodPackageUnit?.defaultPrice }}</view>
						<uni-number-box background="#2979ff" color="#fff" v-model="goodsInfo.num" :min="1"
							:max="foodPackageItem.dayOrderNumberLimit || 99" />
					</view>
					<button type="default" class="add-cart" @click="debounceFunc">
						加入购物车
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { timeToTimestamp, timestampToTime } from '../../utils/data'
import {
	ref,
	getCurrentInstance,
	defineProps,
	onMounted,
	toRefs,
	watch
} from "vue";
import {
	onLoad,
	onReady,
	onPageScroll
} from "@dcloudio/uni-app";
import {
	debounce
} from "../../utils/tool";
import {
	useCartStore,
	useMemberStore,
	useTimeStore
} from "../../stores";
import {
	http
} from "../../utils/http";
// import { Decimal } from 'decimal.js'
const foodPackageItem = ref({}) //套餐
const foodPackageUnit = ref() //套餐单品
const foodItem = ref({})
const prost = defineProps({
	list: {
		type: Object,
		default: {}
	},
	restaurantSerials: {
		type: String,
		default: ''
	},
	current: {
		type: String,
		default: 0
	}
})
const {
	list,
	restaurantSerials,
	current
} = toRefs(prost)
const userStore = useMemberStore()
// 获取套餐详情
const getFoodPackageItemFn = async (foodPackageSerials) => {
	const {
		data, restime
	} = await http({
		url: '/GetFoodPackage',
		method: 'post',
		data: {
			...userStore.requestData,
			data: {
				foodPackageSerials: [foodPackageSerials],
				restaurantSerials: restaurantSerials.value
			}
		}
	})
	foodPackageItem.value = data[0] //接口返回的套餐原数据
	goods.value.sameTypeFreeSign = foodPackageItem.value.sameTypeFreeSign//判断军人身份的标识
	goods.value.goodsInfo.dayOrderNumberLimit = foodPackageItem.value.dayOrderNumberLimit//套餐一天的点单限制数
	const foodlist = data[0].foodlist//套餐对应下的单品
	let foodlistdata = []
	// 去重筛选获取对应类别下的子单品-整合套餐下单品菜单分类下的数据
	foodlist.forEach(element => {
		element.checked = false //套餐内单品的选中状态
		if (foodlistdata.filter(item => item.groupName == element.groupName).length > 0) { } else {
			foodlistdata.push({
				groupName: element.groupName,
				groupChooseFoodNum: element.groupMinChooseFoodNum,
				groupNo: element.groupNo
			})
		}
	});

	foodlistdata.forEach(item => {
		item.foodlist = foodPackageItem.value.foodlist.filter(r => r.groupName == item.groupName)
	})
	foodlistdata = foodlistdata.sort((a, b) => a.groupNo - b.groupNo)//单品排序
	foodPackageUnit.value = {
		defaultPrice: foodPackageItem.value.defaultPrice,
		foodlistdata
	} //套餐弹窗渲染数据
	foodPackageUnit.value.foodlistdata.forEach(item => {
		if (item.foodlist.length == item.groupChooseFoodNum) {
			item.foodlist.forEach(r => {
				r.checked = true
			})
		}
	})
	console.log(foodPackageUnit.value,'foodPackageUnit.value');
}
//获取单品详情
const getFoodItemFn = async (foodSerials) => {
	const storeTime = useTimeStore()
	const {
		data, restime
	} = await http({
		url: '/GetFoods',
		method: 'post',
		data: {
			...userStore.requestData,
			data: {
				foodSerials: [foodSerials],
				restaurantSerials: restaurantSerials.value
			}
		}
	})
	foodItem.value = data[0]
}
// 获取用户点击套餐里面的单品的数据(点击传参：当前点击单品，必选数量，当前分类下单品数量,当前分类数据)
let arr = {}
const foodPack = ref([]) //用户所选套餐单品数据
const fn = (nowFood, reqNum, foodLength, foodData) => {
	console.log(nowFood, reqNum,arr);
	foodPack.value = []
	if (!arr[nowFood.groupName]) arr[nowFood.groupName] = []
	nowFood.checked = !nowFood.checked
	if (arr[nowFood.groupName]?.some(it => it == nowFood)) {
		arr[nowFood.groupName]?.splice(arr[nowFood.groupName].findIndex(itt => itt == nowFood), 1)
		return
	}
	arr[nowFood.groupName]?.push(nowFood)
	console.log(arr[nowFood.groupName]?.length ,reqNum);
	if (arr[nowFood.groupName]?.length > reqNum) {
		arr[nowFood.groupName][0].checked = false
		arr[nowFood.groupName]?.shift()
	}
	Object.keys(arr).forEach(key => {
		const kk = arr[key].filter(item => item.checked == true)
		foodPack.value.push({
			...kk
		})
	});

}
const storeCart = useCartStore();

let windowHeight = ref("0px");
let clickId = ref("");
let clickToId = ref("");
let currentNum = ref(0);
let topList = ref([]);
let isLeftClick = ref(false);
let menuItem = ref([])
let setId = (index) => {
	clickId.value = "po" + index;
	isLeftClick.value = true;
	currentNum.value = index;
};
let scroll = (e) => {
	if (isLeftClick.value) {
		isLeftClick.value = false;
		return;
	}
	let scrollTop = e.target.scrollTop;
	for (let i = 0; i < topList.value.length; i++) {
		let h1 = topList.value[i];
		let h2 = topList.value[i + 1];
		if (scrollTop >= h1 && scrollTop < h2) {
			currentNum.value = i;
			clickToId.value = "to" + i;
		}
		//解决滚动到最后选项左侧不会选中
		let length = topList.value.length;
		if (scrollTop >= topList.value[length - 1]) {
			currentNum.value = length - 1;
			clickToId.value = "to" + length - 1;
		}
	}
};
let getNodesInfo = () => {
	//获取节点为.right_title距离顶部的距离，返回值放在数组中
	const instance = getCurrentInstance(); // 获取组件实例
	let query = uni.createSelectorQuery().in(instance);
	query
		.selectAll(".right_title")
		.boundingClientRect()
		.exec((res) => {
			let nodes = res[0];
			let rel = [];
			nodes.map((item) => {
				rel.push(item.top);
			});
			topList.value = rel;
		});
};
onLoad(() => {
	getNodesInfo();
});
// -------------------------------------------

onMounted(() => {
	uni.getSystemInfo({
		success: function (res) {
			windowHeight.value = res.windowHeight - 100 + "px";
		},
	});
	menuItem.value = [...list.value.foodpackagetypelist, ...list.value.foodtypelist]
})
// 监听餐别变化
watch(() => list.value, (newVal, oldval) => {
	menuItem.value = [...newVal.foodpackagetypelist, ...newVal.foodtypelist]
}, {
	deep: true
})
// // 选中的商品
let goodsInfo = ref({
	num: 1
});
// 添加按钮弹窗显示
const addCartPopup = ref();
const popup = ref();
const goods = ref({})
// 点击添加按钮
const onBtn = (it, item) => {
	let foodId = ''
	
	it.foodPackageSerials ? foodId = it.foodPackageSerials : foodId = it.foodSerials
	goodsInfo.value = {
		...it,
		foodId,
		num: 1
	};
	goods.value = {
		...goods.value,
		menuSerials: item.menuSerials,
		orderCategoryName: item.orderCategoryName,
		orderCategorySerials: item.orderCategorySerials,
		goodsInfo: goodsInfo.value
	}
	if (goodsInfo.value.foodPackageSerials) {
		arr = {} 
		getFoodPackageItemFn(goodsInfo.value.foodPackageSerials)
		// todo套餐单品渲染
		popup.value.open();
	} else {
		getFoodItemFn(goodsInfo.value.foodSerials)
		addCartPopup.value.open();
	}
};
// 购物车数据
const addCart = (i) => {
	const storeCart = useCartStore()
	if (storeCart.cartObj.orderList.length > 0) {
		const hisOrder = storeCart.cartObj.orderList.filter(item => item.foodPackageSerials == goodsInfo.value.foodPackageSerials)
		//  获取当日的历史订单，判断当前选择的套餐是否有超出当日的点餐限制，如果有提示用户已超出,如果没有，不做任何处理 
		if (hisOrder && hisOrder.length > 0) {
			// 超出当日点餐限制-提示用户
			if (hisOrder[0].number == goodsInfo.value.dayOrderNumberLimit) {
				const msg = `该套餐当日仅可点"${goodsInfo.value.dayOrderNumberLimit}"次`
				return uni.showToast({ title: msg, icon: 'none', duration: 2500 })
			}
		}
	}
	if (goodsInfo.value.foodPackageSerials) {
		let normal = false
		let foodlist = []
		foodPackageUnit.value.foodlistdata?.forEach(item => {
			const shuliang = item.foodlist.filter(r => r.checked)
			if (shuliang.length != item.groupChooseFoodNum) {

				normal = true
			}
			shuliang.forEach(r => {
				foodlist.push(r)
			})
		})
		if (normal) {
			uni.showToast({
				title: "请按套餐可选数量勾选",
				icon: "none",
				duration: 1500,
			});
			return false
		} else {
			goods.value.goodsInfo.foodlist = foodlist
			storeCart.cartNew.push({
				...goods.value
			})
		}
	} else {
		// goods.value.dayOrderNumberLimit=foodItem.value.dayOrderNumberLimit
		storeCart.cartNew.push({
			...goods.value
		})
	}

	const cart = ref([])
	const newArray = storeCart.cartNew.reduce((result, item) => {
		cart.value = result.find(i => i.orderCategoryName === item.orderCategoryName);
		if (cart.value) {
			cart.value.goodsInfo.push(item.goodsInfo);
		} else {
			result.push({
				sameTypeFreeSign: item.sameTypeFreeSign,//
				orderCategoryName: item.orderCategoryName,
				menuSerials: item.menuSerials,
				orderCategorySerials: item.orderCategorySerials,
				goodsInfo: [item.goodsInfo]
			});
		}
		return result;
	}, []);
	storeCart.cart = newArray
	uni.showToast({
		title: "加入成功",
		icon: "none",
		duration: 1000,
	});
	// goodsInfo.value.num = 1; //加入购物车后数量改为1
	if (!goodsInfo.value.foodPackageSerials) {
		addCartPopup.value.close(); //单品弹窗关闭
	} else {
		popup.value.close(); //套餐弹窗关闭
	}
};
let debounceFunc = ref();
debounceFunc.value = debounce(addCart, 500);

let twobindChange = (value, it) => {
	let current = 0
	storeCart.cart.forEach((item, i) => {
		item.goodsInfo.forEach(row => {
			if (row.foodId == it.foodPackageSerials || row.foodId == it.foodSerials) {
				current = i
			}
		})
	})
	const index = storeCart.cartNew.findIndex(item => item.goodsInfo.foodId == it.foodPackageSerials || item.goodsInfo.foodId == it.foodSerials)
	const cartindex = storeCart.cart[current].goodsInfo.findIndex(item => item.foodId == it.foodSerials || item.foodId == it.foodPackageSerials)
	if (value < 1) {
		//数量小于1认为是删除
		storeCart.cart[current].goodsInfo.splice(cartindex, 1);
		if (storeCart.cart[current].goodsInfo.length == 0) {
			storeCart.cart.splice(current, 1);
		}
		storeCart.cartNew.splice(index, 1)
	} else {

		storeCart.cart[current].goodsInfo[cartindex].num = value;
		storeCart.cartNew[index].goodsInfo.num = value
	}
};
const clickImg = (url, img) => {
	const kk = 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg'
	uni.previewImage({
		urls: img ? [url] : [kk], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
		current: "", // 当前显示图片的http链接，默认是第一个
	});
};
// 点击右上角按钮关闭弹窗
const onCloseBtn = () => {
	popup.value.close()
}

</script>

<style lang="scss" scoped>
.ld {
	display: flex;
	background-color: #eee;
	height: 100%;

	.left {
		width: 250rpx;
		overflow: scroll;
		background-color: #fff;

		.title {
			text-align: center;
			height: 100rpx;
			line-height: 100rpx;
			color: #000000;
			transition: 0.5s ease-in-out;
			background-color: #fff;
		}

		.active {
			background-color: #ddd;
			border-left: 10rpx #2979ff solid;
		}
	}

	.right {
		box-sizing: border-box;
		// padding-bottom: 60rpx;
		// margin-bottom: 100rpx;
		flex: 1;
		background-color: #fff;
		overflow: auto;
		height: calc(100vh - 230rpx - 100rpx);
		background-color: #eee;

		.goods {
			background-color: #fff;
			margin: 0rpx 6rpx 15rpx 6rpx;
			border-radius: 12rpx;
			padding: 0 20rpx 20rpx 20rpx;
			box-sizing: border-box;
		}

		.title {
			color: #494848;
			padding: 20rpx;
			font-weight: 600;
			font-size: 28rpx;
		}

		.goods-item {
			width: 100%;
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 20rpx 0;

			.goods-info {
				display: flex;
				flex: 1;

				image {
					width: 130rpx;
					height: 130rpx;
					border-radius: 16rpx;
					margin-right: 15rpx;
				}

				.conent {
					padding: 5rpx;
					height: 130rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-around;

					.label {
						padding: 5rpx;
						color: red;
						font-size: 25rpx;
						border: 2rpx solid red;
						text-align: center;
						border-radius: 50rpx;
					}

					.name {
						font-size: 30rpx;
						color: #333;

					}

					.price {

						font-size: 28rpx;


						.price_color {
							color: #37b3fb;
						}
					}
				}
			}

			.number {
				font-size: 24rpx;
				margin-left: 2rpx;
			}

			.add-btn {
				width: 120rpx;
				height: 50rpx;
				padding: 0;
				font-size: 24rpx;
				line-height: 50rpx;
				text-align: center;
				color: #fff;
				border-radius: 12rpx;
				background-color: #2979ff;
			}
		}
	}
}

.add_box {
	image {
		width: 600rpx;
	}

	.goods-name {
		text-align: center;
		font-weight: 600;
		font-size: 32rpx;
	}

	.add-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;

		.price_color {
			color: #cf4444;
		}
	}

	.specifications {
		padding: 0 30rpx;
		color: #333;

		text {
			background-color: #2979ff;
			padding: 5rpx 12rpx;
			border-radius: 18rpx;
			font-size: 32rpx;
			color: #fff;
		}
	}
}

.add-cart {
	margin-bottom: 20rpx;
	background-color: #2979ff;
	width: 400rpx;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 34rpx;
	color: #fff;
}

.picture {
	width: 100rpx;
	position: relative;
}

.image {
	width: 100rpx;
	height: 100rpx;
}

.meal {

	.dot {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		border: 2rpx solid #eee;
		background-color: #fff;
	}

	.grid-item-box {
		// flex: 1;
		// position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}

	.active {
		background-color: red;
	}

	.title {
		font-size: 40rpx;
		text-align: center;
		margin: 45rpx;
	}

	.spec {
		width: 100rpx;
		height: 50rpx;
		margin: 0 20rpx;
		line-height: 50rpx;
		border-radius: 24rpx;
		text-align: center;
		color: #fff;
		background-color: #2979ff;
	}

	.scroll {
		box-sizing: border-box;
		height: 90vh;
		padding: 0 10rpx 340rpx 10rpx;
		background-color: #eee;
	}

	.addcar {
		margin: 30rpx auto;
		width: 300rpx;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: 24rpx;
		text-align: center;
		color: #fff;
		background-color: #2979ff;
	}

	.footer {
		position: fixed;
		width: 100%;
		height: 350rpx;
		box-sizing: border-box;
		bottom: 0;
		background-color: #fff;
		padding: 20rpx;
		box-shadow: -2rpx 0rpx 2px 0rpx rgba(0, 0, 0, 0.5);
	}
}

.close {
	position: relative;

	.img {
		position: absolute;
		top: -42rpx;
		right: 10rpx;
		width: 60rpx;
		height: 60rpx;
	}
}
</style>